<template>
  <div class="play-list f fd-col w-100p h-100p" ref="playlistRef">
    <n-scrollbar class="f fd-col f1 h-0">
      <loading-with-content
        :loading="loading"
        :class="['f fd-col', loading ? 'inset-0' : 'h-fit']"
        content-class="f fd-col"
        spin-class="custom-spin-without-icon spin-description-right"
        ref="contentRef"
      >
        <template #loading-icon><hamster-loader scale="0.8" /></template>
        <template #loading-description><span class="f-sz-14 ml--6">加载中...</span></template>
        <template #content>
          <template v-if="playlistOverview && Object.keys(playlistOverview).length > 0">
            <div class="playlist-overview f mb-14 p-36">
              <section-album :key="id" :is-hover-show-right-bottom-corner="false" :src="playlistOverview.coverImgUrl" wrapperDefaultWidth="200px" />
              <div class="playlist-overview__info-wrapper f f1 w-0 fd-col ml-24">
                <div class="f ai-c mb-10">
                  <span class="tag">歌单</span>
                  <span class="name ml-10 f1 w-0 f-sz-32 f-wt-b line-1-ellipsis">{{ playlistOverview.name }}</span>
                </div>
                <div class="f ai-c mb-10">
                  <div v-if="!!playlistOverview.creator" class="avatar-wrapper h-28">
                    <n-avatar round size="small" :src="playlistOverview.creator.avatarUrl" />
                    <img v-if="!!playlistOverview.creator.avatarDetail" v-img-lazy="playlistOverview.creator.avatarDetail.identityIconUrl" />
                  </div>
                  <span class="ml-10 f-sz-14 cursor-pointer nickname">{{ playlistOverview.creator.nickname }}</span>
                  <span class="ml-10 f-sz-14 us-n">{{ format(playlistOverview.createTime, 'yyyy-MM-dd HH:mm:ss') }}</span>
                </div>
                <div class="f mb-15">
                  <n-button-group>
                    <n-button :focusable="false" round :color="mainBodyColor" :render-icon="renderPlayIcon" class="w-126">播放全部</n-button>
                    <n-button :focusable="false" round :color="mainBodyColor" class="w-38">
                      <template #icon>
                        <n-icon><plus-outlined /></n-icon>
                      </template>
                    </n-button>
                  </n-button-group>
                  <n-button-group class="ml-10">
                    <n-button :focusable="false">
                      <template #icon>
                        <n-icon><folder-plus /></n-icon>
                      </template>
                      <span>收藏</span>
                      <span>(</span>
                      <template v-if="!!playlistOverview.subscribedCount || playlistOverview.subscribedCount === 0">
                        <n-number-animation :from="0" :to="formattedCount(playlistOverview.subscribedCount)" />
                        <span v-if="!!formattedCountUnit(playlistOverview.subscribedCount)">{{ formattedCountUnit(playlistOverview.subscribedCount) }}</span>
                      </template>
                      <span>)</span>
                    </n-button>
                  </n-button-group>
                  <n-button-group class="ml-10">
                    <n-button :focusable="false">
                      <template #icon>
                        <n-icon><share-regular /></n-icon>
                      </template>
                      <span>分享</span>
                      <span>(</span>
                      <template v-if="!!playlistOverview.shareCount || playlistOverview.shareCount === 0">
                        <n-number-animation :from="0" :to="formattedCount(playlistOverview.shareCount)" />
                        <span v-if="!!formattedCountUnit(playlistOverview.shareCount)">{{ formattedCountUnit(playlistOverview.shareCount) }}</span>
                      </template>
                      <span>)</span>
                    </n-button>
                  </n-button-group>
                  <n-button-group class="ml-10">
                    <n-button :focusable="false">
                      <template #icon>
                        <n-icon><cloud-download /></n-icon>
                      </template>
                      下载全部
                    </n-button>
                  </n-button-group>
                </div>
                <div class="f-sz-16 lh-32">
                  <div class="f">
                    <div>
                      <span>歌曲:</span>
                      <span>{{ playlistOverview.trackCount }}</span>
                    </div>
                    <div class="ml-10">
                      <span>播放:</span>
                      <span>
                        <template v-if="!!playlistOverview.playCount || playlistOverview.playCount === 0">
                          <n-number-animation :from="0" :to="formattedCount(playlistOverview.playCount)" />
                          <span v-if="!!formattedCountUnit(playlistOverview.playCount)">{{ formattedCountUnit(playlistOverview.playCount) }}</span>
                        </template>
                      </span>
                    </div>
                  </div>
                  <div v-if="!!playlistOverview.description">
                    <div class="f">
                      <span class="fs-0">简介:</span>
                      <div class="f f1 w-0 jc-sb ai-c">
                        <span class="us-n">
                          {{
                            playlistOverview.description.split('\n').filter((item) => !!item).length > 1
                              ? playlistOverview.description.split('\n')[0] + '...'
                              : playlistOverview.description.split('\n')[0]
                          }}
                        </span>
                        <n-icon
                          v-if="playlistOverview.description.split('\n').filter((item) => !!item).length > 1"
                          :component="isDescriptionCollapsed ? ArrowDropDownSharp : ArrowDropUpSharp"
                          @click="isDescriptionCollapsed = !isDescriptionCollapsed"
                          class="fs-0 cursor-pointer"
                        />
                      </div>
                    </div>
                    <div v-if="playlistOverview.description.split('\n').filter((item) => !!item).length > 1 && !isDescriptionCollapsed">
                      {{ playlistOverview.description.split('\n')[1] }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <n-tabs animated default-value="playlist" class="playlist-tabs">
              <n-tab-pane display-directive="show" name="playlist" :style="playlistPanePaddingRight">
                <template #tab>
                  <div class="custom-tab-wrapper">
                    <span class="custom-tab f-sz-18">歌曲列表</span>
                    <span class="line"></span>
                  </div>
                </template>
                <n-data-table :columns="columns" :data="playlistTableData" :loading="playListLoading" :bordered="false" :row-props="playlistRowProps" striped />
              </n-tab-pane>
              <n-tab-pane display-directive="show" name="comment" :tab="`评论(${playlistOverview.commentCount})`">
                <template #tab>
                  <div class="custom-tab-wrapper">
                    <span class="custom-tab f-sz-18">{{ `评论(${playlistOverview.commentCount})` }}</span>
                    <span class="line"></span>
                  </div>
                </template>
              </n-tab-pane>
              <n-tab-pane display-directive="show" name="collectors" tab="收藏者">
                <template #tab>
                  <div class="custom-tab-wrapper">
                    <span class="custom-tab f-sz-18">收藏者</span>
                    <span class="line"></span>
                  </div>
                </template>
              </n-tab-pane>
            </n-tabs>
          </template>
        </template>
      </loading-with-content>
    </n-scrollbar>
  </div>
</template>

<script setup lang="ts">
  import { storeToRefs } from 'pinia';
  import { NIcon } from 'naive-ui';
  import type { DataTableColumns } from 'naive-ui';
  import { format } from 'date-fns';
  import { useApi } from '@/hooks/useApi';
  import { useGlobalProperties } from '@/hooks/useGlobalProperties';
  import useContainerBeyond from '@/hooks/element/useContainerBeyond';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useDesignSettingStoreOut } from '@/stores/modules/designSetting';
  import { usePlayStoreOut } from '@/stores/modules/play';
  import { INJECTION_SYMBOL_MAIN_BODY_COLOR, formatCount, formatTime } from '@/utils';
  import { SongFeeEnum } from '@/enums/businessEnum';
  import SectionAlbum from '@/views/modules/main/music-discovery/personalized-recommendations/components/section-album.vue';
  import SvgIcon from '@/components/common/svg-icon.vue';
  import { IosPlay } from '@vicons/ionicons4';
  import { PlusOutlined } from '@vicons/antd';
  import { FolderPlus } from '@vicons/tabler';
  import { Share20Regular as ShareRegular, Heart28Regular as HeartRegular } from '@vicons/fluent';
  import { CloudDownload } from '@vicons/carbon';
  import { ArrowDropUpSharp, ArrowDropDownSharp } from '@vicons/material';

  interface Props {
    id?: string;
  }
  type PlaylistOverview = {
    [key: string]: any;
  };
  type RowData = {
    title: string;
    singer: string;
    album: string;
    dt: number;
    [key: string]: any;
  };

  const props = defineProps<Props>();
  const createColumns = (): DataTableColumns<RowData> => {
    return [
      {
        title: '',
        key: 'index',
        minWidth: 40,
        width: 40,
        render(row, index) {
          return playInfo.value.id === row.id
            ? isPlaying.value
              ? h(NIcon, { size: 18, color: appTheme }, () => h(SvgIcon, { name: 'loud-speaker' }))
              : h(NIcon, { size: 18, color: appTheme }, () => h(SvgIcon, { name: 'silent-speaker' }))
            : index < 9
              ? h('span', null, `0${index + 1}`)
              : h('span', null, `${index + 1}`);
        },
      },
      {
        title: '操作',
        key: 'operation',
        render() {
          return h('div', { class: ['f'] }, [
            h(NIcon, { size: 18, component: HeartRegular, onClick: () => {}, title: '喜欢', class: ['ml-4', 'cursor-pointer'] }),
            h(NIcon, { size: 18, component: CloudDownload, onClick: () => {}, class: ['ml-10', 'cursor-pointer'] }),
          ]);
        },
        minWidth: 20,
        width: 70,
      },
      {
        title: '标题',
        key: 'title',
        ellipsis: true,
        width: '35%',
        render: (row) =>
          h('div', { class: ['us-n', 'f ai-c'] }, [
            h('span', { title: row.title }, row.title),
            !!row.fee && SongFeeEnum.vip === row.fee
              ? h('span', null, [
                  h(
                    'span',
                    { class: ['ml-6', 'ph-4 pv-1', 'f-sz-14 lh-14'], style: { color: 'orange', border: `1px solid orange`, borderRadius: '2px' } },
                    'vip'
                  ),
                  h(
                    'span',
                    { class: ['ml-6', 'ph-4 pv-1', 'f-sz-14 lh-14'], style: { color: appTheme, border: `1px solid ${appTheme}`, borderRadius: '2px' } },
                    '试听'
                  ),
                ])
              : '',
            !!row.hr
              ? h(
                  'span',
                  { class: ['ml-6', 'ph-4 pv-1', 'f-sz-14 lh-14'], style: { color: appTheme, border: `1px solid ${appTheme}`, borderRadius: '2px' } },
                  'Hi-Res'
                )
              : '',
            !row.hr && !!row.sq
              ? h(
                  'span',
                  { class: ['ml-6', 'ph-4 pv-1', 'f-sz-14 lh-14'], style: { color: appTheme, border: `1px solid ${appTheme}`, borderRadius: '2px' } },
                  'SQ'
                )
              : '',
            !!row.mv
              ? h(
                  'span',
                  { class: ['ml-6', 'ph-4 pv-1', 'f-sz-14 lh-14', 'f ai-c'], style: { color: appTheme, border: `1px solid ${appTheme}`, borderRadius: '2px' } },
                  [h('span', null, 'MV'), h(NIcon, { component: IosPlay, size: 12, class: ['lh-12'] })]
                )
              : '',
          ]),
      },
      {
        title: '歌手',
        key: 'singer',
        ellipsis: true,
        width: '25%',
        render: (row) => h('span', { class: ['cursor-pointer'], title: row.singer }, row.singer),
      },
      {
        title: '专辑',
        key: 'album',
        ellipsis: true,
        width: '20%',
        render: (row) => h('span', { class: ['cursor-pointer'], title: row.album }, row.album),
      },
      {
        title: '时间',
        key: 'dt',
        width: '15%',
        render(row) {
          const value = formatTime(row.dt);
          return h('span', null, value);
        },
      },
    ];
  };

  const { playlist: playlistApi } = useApi();
  const { $message, $to } = useGlobalProperties();
  const designSettingStore = useDesignSettingStoreOut();
  const { appTheme } = designSettingStore;
  const playStore = usePlayStoreOut();
  const { setSongUrl } = playStore;
  const { playInfo, isPlaying } = storeToRefs(playStore);
  const playlistRowProps = (row, index) => ({
    class: playInfo.value.id === row.id ? 'n-data-table-tr active-play-row' : 'n-data-table-tr',
    onDblclick() {
      playStore.$patch((state) => {
        if (activePlayId.value === row.id && state.isPlaying) {
          $message.warning('已开始播放~');
          return;
        }
        state.isPlaying = true;
        state.playList = playlistTableData.value;
        state.currentPlayIndex = index;
        state.currentProgressTime = 0;
        activePlayId.value = row.id;
        Object.assign(state.playInfo, { ...row, title: row.name, singer: row.singer, durationTime: row.dt, picUrl: row.picUrl });
        setSongUrl();
      });
    },
  });

  const loading = ref(false);
  const playListLoading = ref(false);
  const isDescriptionCollapsed = ref(true);
  const activePlayId = ref(0);
  const playlistTableData = ref([]);
  const playlistRef = ref<Element | null>(null);
  const contentRef = ref<Element | null>(null);
  const mainBodyColor = inject(INJECTION_SYMBOL_MAIN_BODY_COLOR, ref('red'));
  const playlistOverview: PlaylistOverview = reactive({});
  const columns = reactive(createColumns());
  const { isYBeyond } = useContainerBeyond(playlistRef, contentRef);
  const playlistPanePaddingRight = computed(() => (isYBeyond.value ? 'paddingRight:var(--app-scrollbar-width)' : 'paddingRight:0'));

  const renderPlayIcon = () => h(NIcon, null, { default: () => h(IosPlay) });
  const formattedCount = (count) => parseFloat(formatCount(count));
  const formattedCountUnit = (count) => formatCount(count).toString().slice(formattedCount(count).toString().length);
  const loadData = async () => {
    await loadListDetail();
    await loadListAll();
    await loadListDynamicDetail();
  };
  const loadListAll = async () => {
    if (!props.id) return;
    playListLoading.value = true;
    const [error, resp]: [any, any] = await $to(playlistApi.trackAll(30, 0, props.id));
    playListLoading.value = false;
    if (error || resp.code !== ResultEnum.SUCCESS) {
      $message.error(error?.msg || resp?.msg || error);
    }
    if (resp && resp.code === ResultEnum.SUCCESS) {
      const { songs } = resp;
      playlistTableData.value = songs.map((item) => ({
        ...item,
        title: item.name,
        album: item.al.name,
        singer: item.ar.map((it) => it.name).join('/'),
        picUrl: item.al.picUrl,
      }));
      playStore.$patch((state) => {
        state.currentPlayIndex = playlistTableData.value.findIndex((item) => item.id === playInfo.value.id);
      });
      return;
    }
    playlistTableData.value = [];
  };
  const loadListDetail = async () => {
    if (!props.id) return;
    loading.value = true;
    const [error, resp]: [any, any] = await $to(playlistApi.playlistDetail(props.id));
    loading.value = false;
    if (error || resp.code !== ResultEnum.SUCCESS) {
      $message.error(error?.msg || resp?.msg || error);
    }
    if (resp && resp.code === ResultEnum.SUCCESS) {
      const { playlist = {} } = resp;
      Object.assign(playlistOverview, { ...playlist });
      return;
    }
    Object.assign(playlistOverview, {});
  };
  const loadListDynamicDetail = async () => {
    if (!props.id) return;
    const [error, resp]: [any, any] = await $to(playlistApi.dynamicDetail(props.id));
    if (error || resp.code !== ResultEnum.SUCCESS) {
      $message.error(error?.msg || resp?.msg || error);
    }
    if (resp && resp.code === ResultEnum.SUCCESS && resp.data) {
      console.log(resp.data);
      return;
    }
  };

  watch(
    () => props.id,
    () => {
      loadData();
    },
    {
      immediate: true,
      flush: 'post',
    }
  );
</script>

<style lang="scss">
  .play-list {
    .content-wrapper {
      .playlist-overview {
        &__info-wrapper {
          .tag {
            font-size: 18px;
            line-height: 18px;
            color: v-bind(mainBodyColor);
            padding: 4px 8px;
            border: 1px solid v-bind(mainBodyColor);
            border-radius: 4px;
          }
          .avatar-wrapper {
            position: relative;
            .n-avatar {
              width: 28px;
              height: 28px;
            }
            > img {
              position: absolute;
              right: -3px;
              bottom: 0;
              width: 14px;
              aspect-ratio: 1;
            }
          }
          .nickname {
            color: #5091cb;
            &:hover {
              color: #0b58b0;
            }
          }
        }
      }

      .playlist-tabs {
        .n-tabs {
          &-tab__label {
            font-size: 20px;
          }
          &-tab--active {
            .custom-tab-wrapper {
              .custom-tab {
                color: #000;
                font-size: 24px !important;
              }
              .line {
                background-color: v-bind(appTheme);
              }
            }
          }
          &-bar {
            display: none;
          }
          &-wrapper {
            margin-left: 40px;
          }
        }
        .custom-tab-wrapper {
          display: flex;
          flex-direction: column;
          align-items: center;
          .line {
            margin-top: 6px;
            width: 80%;
            height: 4px;
            border-radius: 4px;
          }
        }
      }

      .n-data-table {
        &-wrapper {
          border-top: none;
        }
        &-thead {
          background-color: transparent;
          > tr {
            > th {
              padding: 6px 12px;
              background-color: transparent;
            }
          }
        }
        &-tr {
          > td {
            padding: 6px 12px;
          }
        }

        .active-play-row {
          > td {
            background-color: #e5e5e5;
          }
        }
      }
    }
  }
</style>
